package frameworks.business
{
	import mx.controls.Alert;
	import mx.events.CloseEvent;

	public class RequestConnect
	{
		protected var _request:RequestItem;
		
		
		public function RequestConnect()
		{
		}
		
		public function set request(item:RequestItem):void{
			if(_request==null){
				_request = item;
				this[_request.method].apply(null, item.arguments);	
			}
		}
		protected function connect():void{
			
		}
		protected function connectProgress(data:Object):void{
			
		}
		protected function connectSuccess(code:Object):void{
			if(code is String){
				var e:Object;
				var str:String = String(code);
				var arr:Array = str.split("êêê");
				try{
					code = JSON.parse(arr[0]);
					if(_request.result && code.valid){
						code.data = new _request.result(code.data);
					}
					arr.shift();
					code.attachment = arr;
				}catch(e:Object){
					code = {};
					code.valid = false;
					code.data = "";
					code.errors = {p01 : _request.label + ":" + Language.LoadErrorFormat};
					code.attachments = [];
				}
				code.source = str;
			}
			var result:RequestResult = new RequestResult(code);
			if(result.valid){
				_request.setSuccessData(result);
			}else{
				_request.setErrorData(result);
			}
			_request = null;
		}
		protected function connectError(errors:Object):void{
			Alert.yesLabel = Language.RequestYesLabel;
			Alert.cancelLabel = Language.RequestCancelLabel;
			Alert.show(_request.label+errors+Language.LoadRetryLabel, Language.ErrorTitlePop,Alert.YES|Alert.CANCEL,null,isRetryLoad);
			Alert.yesLabel = Language.YesLabel;
			Alert.cancelLabel = Language.CancelLabel;
		}
		private function isRetryLoad(event:CloseEvent):void{
			if(event.detail==Alert.YES){
				var request2:RequestItem = _request;
				_request = null;
				this.request = request2;
			}else{
				var errors:Array = [ _request.label + Language.LoadErrorCancel];
				var obj:Object = null;
				if(_request.label == Language.LoadImageLabel){
					obj = new _request.result( new Setting.PicLoadError(),"pic_load_error");
				}
				var result:RequestResult = new RequestResult({valid:false,data:obj,errors:errors});
				_request.setErrorData(result);
				_request = null;
			}
		}
	}
}